package com.lagou.request;

import com.lagou.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author yongting zhang
 * @date 2020-06-12 10:43
 */
public class RpcDecoder extends ByteToMessageDecoder {
    private static final int LENGTH = 4;
    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (clazz != null) {
            int size = byteBuf.readInt();
            byte[] bytes = new byte[size];
            byteBuf.readBytes(bytes);
            Object obj = serializer.deserialize(clazz, bytes);
            list.add(obj);
        }

    }
}
